<template>
  <a-modal
      title="重置密码"
      :width="320"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleSubmit"
      @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
            label="输入密码"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
        >
          <a-input-password
              v-decorator="['loginPwd', {rules: [
              { required: true, message: '请输入登录密码', trigger: 'blur' },]}]"/>
        </a-form-item>
        <a-form-item
            label="确认密码"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
        >
          <a-input-password
              v-decorator="['loginPwd2', {rules: [
              { required: true, message: '请再次确认密码', trigger: 'blur' },
              { validator: validatePwd2, trigger: 'blur' }]}]"/>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import {resetPwd} from '@/api/basic/user'
import md5 from 'md5'

export default {
  data () {
    return {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      visible: false,
      confirmLoading: false,
      userId: 0,

      form: this.$form.createForm(this)
    }
  },
  methods: {
    resetPwd (userId) {
      this.visible = true
      this.userId = userId
    },
    // 前端两次密码是否一致
    validatePwd2 (rule, value, callback) {
      if (value === '' || value === undefined || value === null) {
        callback()
      } else {
        if (this.form.getFieldValue('loginPwd') === value) {
          return callback()
        } else {
          return callback(new Error('请确保两次密码输入一致'))
        }
      }
    },
    handleSubmit () {
      const {form: {validateFields}} = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          values.loginPwd = md5(values.loginPwd)
          delete values.loginPwd2
          resetPwd(Object.assign(values, {'userId': this.userId}))
              .then(() => {
                this.visible = false
                this.confirmLoading = false
                this.form.resetFields()
                this.$message.success('密码重置成功！')
              }).catch(err => {
            this.confirmLoading = false
            this.$message.error(err.result || '操作失败！')
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.form.resetFields()
      this.visible = false
    }
  }
}
</script>
